package ws.very.android.util.async;

import android.os.Looper;
import android.os.Message;

import ws.very.util.lang.function.Fn;

public class ThreadFns {
	public final static RunHandler main = new RunHandler(Looper.getMainLooper());

	public static boolean isCurMain() {
		return Looper.getMainLooper() == Looper.myLooper();
	}

	public static <I> Fn<I, Void> makeMain(final ws.very.util.lang.function.Fn<I, ?> old) {

		return new Fn<I, Void>() {

			@Override
			public Void apply(final I in) {
				if (isCurMain()) {
					old.apply(in);
					return null;
				}
				Message message = Message.obtain();
				message.obj = new Runnable() {

					@Override
					public void run() {
						old.apply(in);
					}
				};
				main.sendMessage(message);
				return null;
			}

		};
	}

	public static <I> Fn<I, Void> makeBackground(final Fn<I, ?> old) {
		return new Fn<I, Void>() {

			@Override
			public Void apply(I in) {
				if (!isCurMain()) {
					old.apply(in);
				} else
					voidRun(old, in);
				return null;
			}

		};

	}

	private static <I> void voidRun(final Fn<I, ?> old, final I in) {
		Pools.cached.execute(new Runnable() {

			@Override
			public void run() {
				old.apply(in);
			}
		});
	}

	public static <I, O> Fn<I, Void> makeAsync(final Fn<I, ?> old) {
		return new Fn<I, Void>() {

			@Override
			public Void apply(final I in) {
				voidRun(old, in);
				return null;
			}

		};
	}
}
